package mp

import (
	"context"
	"fmt"

	"ruikc.com/server/api/internal/svc"
	"ruikc.com/server/api/internal/types"
	"ruikc.com/server/models"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeptListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDeptListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeptListLogic {
	return &DeptListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DeptListLogic) DeptList() (resp []*types.DeptList, err error) {
	resp = l.fetchChildren(0)

	return resp, nil
}

func (l *DeptListLogic) fetchChildren(pid int64) []*types.DeptList {
	var datas []*models.Dept
	err := l.svcCtx.Db.Where("pid = ? ", pid).Find(&datas)
	if err != nil {
		fmt.Println("Error fetching children:", err)
		return nil
	}
	result := []*types.DeptList{}
	for _, v := range datas {
		tmp := &types.DeptList{
			Id:       v.Id,
			Title:    v.Title,
			Level:    v.Level,
			Tier:     v.Tier,
			Pid:      v.Pid,
			Children: l.fetchChildren(int64(v.Id)),
		}
		result = append(result, tmp)
	}

	return result
}
